import React, { useState, useEffect, useRef } from "react";
import footprint from "../style/footprint.module.css";
import { useNavigate } from "react-router-dom";
import leftImg from "../img/left.png";
import { Calendar, CalendarRef } from "antd-mobile";
import { DownOutline, UpOutline } from "antd-mobile-icons";
import { Me_spoor } from "../api/me";
interface Product {
  id: number;
  title?: string;
  synopsis?: string;
  price: number | string;
  original_price?: number | string;
  img?: string;
}

interface SpoorItem {
  date: string;
  list: Product[];
}

interface ApiResponse {
  code: number;
  data: SpoorItem[];
}

type CalendarStyle = React.CSSProperties & {
  "--cell-border-radius"?: string;
  "--cell-height"?: string;
  "--cell-width"?: string;
  "--adm-color-primary"?: string;
  "--adm-color-fill-content"?: string;
  "--header-height"?: string;
  "--title-font-size"?: string;
  "--head-cell-height"?: string;
};

function FootprintPage() {
  const navigate = useNavigate();
  const [user] = useState(() =>
    JSON.parse(localStorage.getItem("user") || "{}")
  );
  const [spoorData, setSpoorData] = useState<SpoorItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [isCalendarExpanded, setIsCalendarExpanded] = useState(false);
  const [today] = useState(new Date());
  const calendarRef = useRef<CalendarRef>(null);

  // Format date display
  const formatDisplayDate = (dateString: string): string => {
    const date = new Date(dateString);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  };

  // Fetch footprint data
  const fetchData = async () => {
    if (!user?.data?.id || !user?.data?.token) {
      setError("用户信息缺失，请重新登录");
      setLoading(false);
      return;
    }

    try {
      const res = await Me_spoor(
        { uid: user.data.id }, // 第一个参数：data
        { Authorization: user.data.token } // 第二个参数：headers
      );

      console.log("接口返回数据:", res.data); // 打印完整数据

      if (res.data.code === 1) {
        setSpoorData(res.data.data || []); // 如果 data 为 null，设置为空数组
      } else {
        setError("获取数据失败");
      }
    } catch (error) {
      console.error("数据获取失败:", error);
      setError("数据加载失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [user?.data?.id, user?.data?.token]);

  // Handle date selection
  const handleDateSelect = (val: Date | null) => {
    if (val) {
      setSelectedDate(val);
    }
  };

  // Filter data for selected date
  const filteredData = spoorData.filter((item) => {
    const itemDateStr = item.date.split("T")[0];
    const selectedDateStr = selectedDate.toISOString().split("T")[0];
    return itemDateStr === selectedDateStr;
  });

  const goBack = () => navigate(-1);

  // Render calendar date cell
  const renderDate = (date: Date) => {
    const dateStr = date.toISOString().split("T")[0];
    const hasData = spoorData.some(
      (item) => item.date.split("T")[0] === dateStr
    );
    const isToday = today.toDateString() === date.toDateString();
    const isSelected = selectedDate.toDateString() === date.toDateString();

    let cellStyle: React.CSSProperties = {
      borderRadius: "50%",
      padding: "4px",
      width: "32px",
      height: "32px",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
    };

    if (isSelected) {
      cellStyle.backgroundColor = "#FF8000";
      cellStyle.color = "white";
    } else if (isToday) {
      cellStyle.backgroundColor = "rgb(212 205 205)";
      cellStyle.color = "black";
    }

    return (
      <div
        style={{ height: "100%", display: "flex", flexDirection: "column" }}
        data-date={dateStr}
      >
        <div
          style={{
            flex: 1,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <div style={cellStyle}>{date.getDate()}</div>
        </div>
      </div>
    );
  };

  // Calendar style configuration
  const calendarStyle: CalendarStyle = {
    "--cell-border-radius": "50%",
    "--cell-height": "48px",
    "--cell-width": "48px",
    "--adm-color-primary": "transparent",
    "--adm-color-fill-content": "transparent",
    "--header-height": "0", // 隐藏年月标题
    "--title-font-size": "0", // 隐藏年月标题
    "--head-cell-height": "36px", // 星期行高度
    fontSize: "var(--adm-font-size-7)",
  };

  // Get empty state message
  const getEmptyMessage = () => {
    if (selectedDate.toDateString() === today.toDateString()) {
      return "今天暂无足迹记录";
    }
    return `${
      selectedDate.getMonth() + 1
    }月${selectedDate.getDate()}日暂无足迹记录`;
  };

  // Calculate default height (week header + one row)
  const getDefaultHeight = () => {
    return 36 + 48; // week header height + row height
  };

  // Scroll to today's date when calendar is loaded
  useEffect(() => {
    if (calendarRef.current) {
      setTimeout(() => {
        const todayCell = document.querySelector(
          `[data-date="${today.toISOString().split("T")[0]}"]`
        );
        todayCell?.scrollIntoView({ block: "nearest", inline: "center" });
      }, 100);
    }
  }, [isCalendarExpanded, today]);
  // 跳转到商品详情
  const handleItemClick = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    // 跳转到详情页面
    navigate("/detail");
  };
  return (
    <div className={footprint.container}>
      <div className={footprint.top}>
        <div>
          <img onClick={goBack} src={leftImg} alt="" />
          <b>足迹</b>
        </div>
      </div>

      <div className={footprint.calendarContainer}>
        <div
          className={`${footprint.calendarWrapper} ${
            isCalendarExpanded ? footprint.expanded : ""
          }`}
          style={{
            height: isCalendarExpanded ? "auto" : `${getDefaultHeight()}px`,
            overflow: "hidden",
          }}
        >
          <Calendar
            ref={calendarRef}
            selectionMode="single"
            value={selectedDate}
            onChange={handleDateSelect}
            renderDate={renderDate}
            weekStartsOn="Monday"
            style={calendarStyle}
          />
        </div>

        <div
          className={footprint.expandButton}
          onClick={() => setIsCalendarExpanded(!isCalendarExpanded)}
        >
          {isCalendarExpanded ? (
            <>
              <UpOutline /> 收起日历
            </>
          ) : (
            <>
              <DownOutline /> 展开日历
            </>
          )}
        </div>
      </div>

      {loading && <div className={footprint.loading}>加载中...</div>}
      {error && <div className={footprint.error}>{error}</div>}

      <div className={footprint.listContainer}>
        {!loading && !error && filteredData.length === 0 && (
          <div className={footprint.empty}>{getEmptyMessage()}</div>
        )}

        {filteredData.map((spoorItem) => (
          <div key={spoorItem.date} className={footprint.dateGroup}>
            <div className={footprint.dateHeader}>
              {formatDisplayDate(spoorItem.date)}
            </div>
            <div className={footprint.itemsContainer}>
              {spoorItem.list.map((product) => (
                <div
                  key={product.id}
                  className={footprint.productItem}
                  onClick={() => handleItemClick(product.id)}
                >
                  <img
                    src={product.img || "/default-product.png"}
                    alt={product.title || "商品图片"}
                    className={footprint.productImage}
                    onClick={() => navigate(`/product/${product.id}`)}
                    onError={(e) => {
                      (e.target as HTMLImageElement).src =
                        "/default-product.png";
                    }}
                  />
                  <div className={footprint.productInfo}>
                    <h3 className={footprint.productTitle}>
                      {product.title || "未命名商品"}
                    </h3>
                    <div className={footprint.priceContainerBig}>
                      <p className={footprint.productSynopsis}>
                        {product.synopsis || "暂无商品描述"}
                      </p>
                      <div className={footprint.priceContainer}>
                        <span className={footprint.currentPrice}>
                          ¥
                          {typeof product.price === "number"
                            ? product.price.toFixed(2)
                            : product.price || "0.00"}
                        </span>
                        {product.original_price && (
                          <del className={footprint.originalPrice}>
                            ¥
                            {typeof product.original_price === "number"
                              ? product.original_price.toFixed(2)
                              : product.original_price}
                          </del>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FootprintPage;
